package npmsearch

import (
	"bytes"
	"fmt"
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
)

func GetHttpData(url string) []byte {
	resp, err := http.Get(url)
	if err != nil {
		return nil
	}

	var buffer bytes.Buffer

	io.Copy(&buffer, resp.Body)

	return buffer.Bytes()
}

func index(c *gin.Context) {
	c.HTML(http.StatusOK, "npm-search.html", gin.H{})
}

func search(c *gin.Context) {
	query := c.Query("q")

	url := fmt.Sprintf("https://www.npmjs.com/search?q=%s", query)

	// data := GetHttpData(url)

	var client = &http.Client{}

	req, _ := http.NewRequest(http.MethodGet, url, nil)
	req.Header = map[string][]string{
		"x-spiferack": {"1"},
	}
	resp, _ := client.Do(req)
	// resp.Body.Read(data)

	var data bytes.Buffer
	io.Copy(&data, resp.Body)

	if data.Len() == 0 {
		c.JSON(http.StatusOK, []gin.H{})
		return
	}

	// var result []interface{}
	// json.Unmarshal(data.Bytes(), &result)

	c.String(http.StatusOK, data.String())
}
